#ifndef __THREADPOOL_H__
#define __THREADPOOL_H__

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "list.h"
#include "lock.h"
#include "wait.h"
#include "elog.h"

#define THREADPOOL_MAX_TASK_NUM 128

// 任务结构体
struct thread_pool_task {
    struct list_head head;
    void (*function)(void *);
    void *arg;
};

struct threadpool_config{
    uint32_t id;
    uint32_t enable;
    /*param*/
    uint32_t num_threads;
};

struct threadpool;

enum THREADPOOL_EVENT
{
    THREADPOOL_EVENT_NONE = 0,
    THREADPOOL_EVENT_TEST,
    THREADPOOL_EVENT_MAX,
};

typedef int32_t (*threadpool_event_notify)(struct threadpool*, int32_t, void*, void*);

struct threadpool_event_action
{
    threadpool_event_notify notify;
    void* object;
    struct threadpool_event_action* next;
};

struct threadpool_operation
{
    int32_t (*init)(struct threadpool*);
    int32_t (*release)(struct threadpool*);

    int32_t (*start)(struct threadpool*, struct threadpool_config *);
    int32_t (*stop)(struct threadpool*);

    int32_t (*add_task)(struct threadpool*, void (*function)(void*), void*);
    int32_t (*drain_tasks)(struct threadpool*);
    int32_t (*status)(struct threadpool* pthreadpool);

    int32_t (*put_task)(struct threadpool*, struct list_head*, struct thread_pool_task*);
	struct thread_pool_task* (*get_task)(struct threadpool*, struct list_head*);

    int32_t (*register_notify)(struct threadpool*, int32_t, threadpool_event_notify notify, void*);
    int32_t (*unregister_notify)(struct threadpool*, int32_t, void*);
    int32_t (*trigger_notify)(struct threadpool*, int32_t, void*);
};

struct threadpool
{
    struct list_head head;
    wait_t wait;
    lock_t lock;
    lock_t notify_lock;

    int running_flag;
    pthread_t pid;

    uint8_t id;
    uint8_t enable;

    struct threadpool_operation* op;
    struct threadpool_event_action *paction[THREADPOOL_EVENT_MAX];
    
    /*private*/
    int num_threads;                // 线程总数
    int active_count;               // 活跃线程数
    int idle_count;                 // 空闲线程数
    bool shutdown;                  // 关闭标志
    bool drain;                     // 排空标志
    pthread_t *workers;             // 工作线程数组
    struct list_head task_free_queue;
    struct list_head task_busy_queue;
    struct thread_pool_task task[THREADPOOL_MAX_TASK_NUM];

    /*public*/
    struct threadpool_config *pcfg;
};

int32_t create_init_threadpool(struct threadpool** pthreadpool);
void release_destroy_threadpool(struct threadpool* pthreadpool);
        
#ifdef __cplusplus
}
#endif

#endif
